package tpoo.client.controllers.handlers;

import static tpoo.common.services.utils.ServiceConstants.*;
import java.net.InetAddress;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;

import tpoo.client.ui.dialogs.LoginDialog;
import tpoo.client.ui.views.ContactsView;
import tpoo.common.dto.model.exception.users.FailedLoginException;
import tpoo.common.dto.model.users.UserDTO;
import tpoo.common.services.UserService;
import tpoo.common.services.exceptions.ServiceException;
import tpoo.common.services.utils.ServiceAdmin;
import tpoo.common.services.utils.ServiceConstants;
import tpoo.common.utils.Listener;
import tpoo.common.utils.UserSession;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * 
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class LoginHandler extends AbstractHandler {
	/**
	 * The constructor.
	 */
	public LoginHandler() {
	}

	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil
				.getActiveWorkbenchWindowChecked(event);

		LoginDialog loginDialog = new LoginDialog(window.getShell());

		if (loginDialog.open() == IDialogConstants.OK_ID) {
			UserService us;
			try {
				us = (UserService) ServiceAdmin.getService(USER_SERVICE);
				us.login(
						loginDialog.getUsername(),
						loginDialog.getPassword(), 
						Listener.getListener().getIp(), 
						Listener.getListener().getPort());
			} catch (FailedLoginException e) {
				MessageDialog.openError(window.getShell(), "Error en login", e.getMessage());
				if (count < 3) { count++; this.execute(event);} else count=0;
				throw new ExecutionException(e.getMessage());
			} catch (Exception e) {
				e.printStackTrace();
				throw new ExecutionException(e.getMessage());
			} 
			
			return loginDialog.getUsername();
		} else
			return null;
	}
	private int count=0;
}
